<script setup lang="ts">
  import { Field } from 'vee-validate';
  import { useSendSmsCode } from '@/hooks/core/useSendSmsCode';
  import { watch } from 'vue';
  import { useLocale } from '@/locales/useLocale';
  const { t } = useLocale();
  const props = withDefaults(
    defineProps<{
      name: string;
      placeholder?: string;
      label?: string;
      interval?: number;
      totalInterval?: number;
      requiredField?: boolean;
      size?: 'large' | 'small' | 'default';
      animateClass?: string;
    }>(),
    {
      name: 'default',
      label: '',
      placeholder: '',
      interval: 1,
      totalInterval: 60,
      requiredField: false,
      size: 'default',
      animateClass: '',
    }
  );
  const emits = defineEmits(['sendSms']);

  const { start, counter, isActive } = useSendSmsCode(props.interval, props.totalInterval);

  const handleSendSms = (value: string) => {
    start();
    emits('sendSms', value);
  };
</script>

<template>
  <Field :name="name" v-slot="{ value, field, errorMessage }">
    <el-form-item
      :error="errorMessage"
      :label="label && t(label)"
      :class="{ 'field-required': requiredField, [animateClass]: animateClass }"
      :size="size"
    >
      <div class="flex justify-between items-center w-full">
        <el-input
          class="!w-[65%]"
          :placeholder="placeholder && t(placeholder)"
          :model-value="value"
          v-bind="field"
        />
        <el-button
          :disabled="!value || isActive"
          @click="handleSendSms(value)"
          class="w-[30%] h-8 sm:h-fit relative rounded shadow cursor-pointer"
          type="success"
          plain
        >
          <slot name="buttonContent">发送短信</slot>
          <div
            class="absolute inset-0 bg-gray-300/70 flex-justify-items-center text-green-500/80 text-xm"
            v-if="isActive"
          >
            <span class="align-middle text-base font-bold sm:text-lg sm:mr-0.5">
              {{ totalInterval - counter - interval }}
            </span>
            <span class="align-middle hidden sm:font-semibold sm:inline">后可重新发送</span>
          </div>
        </el-button>
      </div>
    </el-form-item>
  </Field>
</template>

<style lang="scss"></style>
